package org.mch.func.file.coding;

import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.mch.biz.ui.BizEvent;
import org.mch.comm.exec.MsgException;
import org.mozilla.universalchardet.UniversalDetector;

/**
 * 描述：<BR>
 * 
 * @author MCH；<BR>
 * 
 */
public class ClientEvent extends BizEvent {

	private static final long serialVersionUID = 1L;

	public ClientEvent(ClientPanel panel) {
		super(panel);
	}

	protected void buttonClicked(MouseEvent e) throws Exception {
		// getPanel().setEnabled(false);
		// WaitDialog loadDlg = new WaitDialog("正在转换中，请等待......");
		// loadDlg.start();
		// try {
		if (e.getSource() == getPanel().getBtn_execute()) {
			// 执行业务方法
			onExecute();

		}
		// } finally {
		// loadDlg.end();
		// }
	}

	private void onExecute() throws Exception {
		String old_folder_path = getPanel().getTextChooser_Old().getValue();
		String new_folder_path = getPanel().getTextChooser_New().getValue();
		if (StringUtils.isEmpty(old_folder_path) || StringUtils.isEmpty(new_folder_path)) {
			throw new MsgException("请选择好原文件夹与输出文件夹！");
		}

		File old_folder = new File(old_folder_path);
		// File new_folder = new File(new_folder_path);

		// 获得需要转换编码的文件类型
		Set<String> fileSuffixSet = new HashSet<String>();
		String filetype = getPanel().getText_filetype().getText();
		String[] fts = filetype.split("\n");
		for (String ft : fts) {
			fileSuffixSet.add(ft.toLowerCase());// 规定所有均小写比较
		}

		String old_coding = null;
		String new_coding = null;

		Map<String, String> strRepMap = new HashMap<String, String>();

		Object selObj = getPanel().getComboConverType().getValue();
		if ("GBK To UTF-8".equals(selObj)) {
			old_coding = "GBK";
			new_coding = "UTF-8";

			String gtuss = getPanel().getText_gbkToUTF8().getText();
			String[] gtusps = gtuss.split("\r\n");
			for (String gs : gtusps) {
				String[] ss = gs.split("=");
				strRepMap.put(ss[0], ss[1]);
			}
		} else if ("UTF-8 To GBK".equals(selObj)) {
			old_coding = "UTF-8";
			new_coding = "GBK";

			String utgss = getPanel().getText_utf8ToGBK().getText();
			String[] utgsps = utgss.split("\r\n");
			for (String us : utgsps) {
				String[] ss = us.split("=");
				strRepMap.put(ss[0], ss[1]);
			}
		}

		File[] files = old_folder.listFiles();

		converFileCoding(files, fileSuffixSet, old_coding, new_coding, old_folder_path, new_folder_path, strRepMap);
	}

	protected void converFileCoding(File[] files, Set<String> fileSuffixSet, String old_coding, String new_coding,
			String old_folder_path, String new_folder_path, Map<String, String> strRepMap) throws Exception {

		for (File f : files) {
			String path = f.getPath();
			if (f.isFile()) {

				// 得到当前文件后缀名
				String file_suffix = path.substring(path.lastIndexOf(".") + 1, path.length());

				if (fileSuffixSet.contains(file_suffix.toLowerCase())) {

					boolean isUTF8 = isUTF8File(f);// 当前文件是否为UTF-8编码

					if ("UTF-8".equalsIgnoreCase(new_coding) && isUTF8) {
						/*
						 * 如果当前是将GBK转UTF-8，则判断文件是不是本身就是UTF-8，如果是，则直接复制；
						 */
						File new_file = new File(path.replace(old_folder_path, new_folder_path));
						FileUtils.copyFile(f, new_file);
						continue;
					} else if (("GB18030".equalsIgnoreCase(new_coding) || "GB2312".equalsIgnoreCase(new_coding) || "GBK"
							.equalsIgnoreCase(new_coding)) && !isUTF8) {
						/*
						 * 如果当前是将UTF-8转GBK，则判断文件是不是本身就是UTF-8，如果不是，则直接复制；
						 */
						File new_file = new File(path.replace(old_folder_path, new_folder_path));
						FileUtils.copyFile(f, new_file);
						continue;
					}

					// 文件内容，编码转换
					String old_file_data = FileUtils.readFileToString(f, old_coding);
					String new_file_data = new String(old_file_data.getBytes(new_coding), new_coding);

					String[] keys = strRepMap.keySet().toArray(new String[0]);
					for (String key : keys) {
						new_file_data = new_file_data.replace(key, strRepMap.get(key));
					}

					File new_file = new File(path.replace(old_folder_path, new_folder_path));

					FileUtils.writeStringToFile(new_file, new_file_data, new_coding);
				} else {
					// 对不进行转换的文件处理，如果选择原文件拷贝则进行拷贝操作
					if (getPanel().getCheck_iscopynotconverfile().isSelected()) {
						File new_file = new File(path.replace(old_folder_path, new_folder_path));
						FileUtils.copyFile(f, new_file);
					}
				}

			} else if (f.isDirectory()) {
				File new_folder = new File(path.replace(old_folder_path, new_folder_path));
				new_folder.mkdir();
				File[] child_files = f.listFiles();

				converFileCoding(child_files, fileSuffixSet, old_coding, new_coding, old_folder_path, new_folder_path,
						strRepMap);
			}
		}
	}

	/**
	 * 返回 true ，则当前文件是UTF-8编码；
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public boolean isUTF8File(File file) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		UniversalDetector detector = new UniversalDetector(null);

		try {
			// (2)
			int nread;
			byte[] buf = new byte[4096];
			while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
				detector.handleData(buf, 0, nread);
			}
			// (3)
			detector.dataEnd();

			// (4)
			String encoding = detector.getDetectedCharset();

			if ("UTF-8".equalsIgnoreCase(encoding)) {
				return true;
			} else {
				return false;
			}
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}

	public ClientPanel getPanel() {
		return (ClientPanel) super.getPanel();
	}

}